/**
 * Created by wust on 2020-03-31 09:13:01
 * Copyright © 2020 wust. All rights reserved.
 */
package com.wust.smartcity.admin.server.core.service.impl;


import com.wust.smartcity.admin.server.core.dao.SysDataSourceMapper;
import com.wust.smartcity.common.entity.sys.datasource.SysDataSource;
import com.wust.smartcity.common.service.InitializtionService;
import com.wust.smartcity.common.util.MyStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;

/**
 * @author: wust
 * @date: Created in 2020-03-31 09:13:01
 * @description:
 *
 */
@Order(0)
@Service
public class InitData4DataSourceServiceImpl implements InitializtionService {
    @Autowired
    private SysDataSourceMapper sysDataSourceMapper;

    @Autowired
    private Environment environment;

    @Transactional(rollbackFor=Exception.class)
    @Override
    public void init() {
        String applicationName = environment.getProperty("spring.application.name");
        String dbGroupName = environment.getProperty("db-group-name");
        String dbDefaultName = environment.getProperty("db-default-name");
        if(MyStringUtils.isNotBlank(MyStringUtils.null2String(dbDefaultName))){

            String url = environment.getProperty("spring.datasource.druid.url");
            String username = environment.getProperty("spring.datasource.druid.username");
            String password = environment.getProperty("spring.datasource.druid.password");
            String driverClassName = environment.getProperty("spring.datasource.druid.driver-class-name");

            SysDataSource dataSource = new SysDataSource();
            dataSource.setGroupName(dbGroupName);
            dataSource.setName(dbDefaultName);
            dataSource.setJdbcUrl(url);
            dataSource.setJdbcUsername(username);
            dataSource.setJdbcPassword(password);
            dataSource.setJdbcDriver(driverClassName);
            dataSource.setMasterSlave("default");
            dataSource.setDescription(applicationName);
            dataSource.setCreateTime(new Date());

            SysDataSource dataSourceSearch = new SysDataSource();
            dataSourceSearch.setGroupName(dbGroupName);
            dataSourceSearch.setName(dbDefaultName);
            SysDataSource dataSource1 = sysDataSourceMapper.selectOne(dataSourceSearch);
            if(dataSource1 == null){
                sysDataSourceMapper.insert(dataSource);
            }
        }
    }
}
